<template>
  <div class="common-layout">
    <Header/>
    <el-container id="container">
      <el-tabs type="border-card" id="tabs">
        <el-tab-pane label="个人资料">
          <div class="tabDiv">
            <el-form ref="userInfoRef"
                     label-width="auto"
                     :model="userChange"
                     :rules="userInfoRules"
                     id="infoForm"
                     class="formInput">
              <el-form-item style="height: 100px;">
                <!-- el-upload组件用于上传头像，隐藏相关默认显示内容 -->
                <!--这里ref不能用动态绑定,否则proxy.$refs.uploadRef获取不到-->
                <el-upload
                    v-model:file-list="fileList"
                    ref="uploadRef"
                    :action="baseIp+':9090/upload/uploadFile'"
                    :show-file-list="false"
                    :auto-upload="false"
                    accept=".jpg,.jpeg,.png,.bmp"
                    :on-change="handleFileChange"
                    :on-success="handleSuccess"
                    :on-error="handleError"
                    style="margin:0 auto;"
                ><!--:on-exceed="handleExceed"-->
                  <!--:limit="1"-->
                  <el-tooltip
                      class="box-item"
                      effect="light"
                      content="点击修改头像"
                      placement="top-start"
                  >
                    <el-avatar :size="100" :src="uPicUrl"/>
                  </el-tooltip>
                </el-upload>
              </el-form-item>
              <el-form-item label="注册时间" label-position="left" class="formInput" prop="uCreatedAt">
                <el-input v-model="loginUser.uCreatedAt" disabled/>
              </el-form-item>
              <el-form-item label="用户名" label-position="left" class="formInput" prop="username">
                <el-input v-model="userChange.username" autocomplete="off"/>
              </el-form-item>
              <el-form-item label="昵称" label-position="left" class="formInput" prop="displayName">
                <el-input v-model="userChange.displayName" autocomplete="off"/>
              </el-form-item>
              <el-form-item label="手机号" label-position="left" class="formInput" prop="phone">
                <el-input v-model="userChange.phone" autocomplete="off"/>
              </el-form-item>
              <el-form-item class="formButton">
                <el-button type="primary" @click="handleUserChange">
                  保存
                </el-button>
                <el-button @click="cancelUserChange">
                  取消
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
        <el-tab-pane label="修改密码">
          <div class="tabDiv">
            <el-form
                ref="passwordRef"
                :model="passwordChange"
                :rules="changePasswordRules"
                label-width="auto"
                size="large">
              <el-form-item label="旧密码" label-position="left" prop="oldPassword">
                <el-input type="password" v-model="passwordChange.oldPassword"
                          placeholder="请输入旧密码" clearable/>
              </el-form-item>
              <el-form-item label="新密码" label-position="left" prop="newPassword">
                <el-input type="password" v-model="passwordChange.newPassword"
                          placeholder="请输入新密码" clearable/>
              </el-form-item>
              <el-form-item label="确认新密码" label-position="left" prop="confirmNewPassword">
                <el-input type="password" v-model="passwordChange.confirmNewPassword"
                          placeholder="请确认新密码" clearable/>
              </el-form-item>
              <el-form-item class="formButton">
                <el-button type="primary" @click="handleChangePassword">
                  保存
                </el-button>
                <el-button @click="cancelChangePassword">
                  取消
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-container>
  </div>
</template>
<script setup>
import {ref, reactive, inject, getCurrentInstance} from "vue";
import {useRoute, useRouter} from "vue-router";
import Header from "@/components/Header.vue";
import axios from "axios";
import qs from "qs";
import {ElNotification, ElUpload, genFileId} from "element-plus";
import sessionStorage from "@/SessionStorage.js";
import request from "@/request.js";

const baseIp = import.meta.env.VITE_APP_API_URL;
// 图片前缀全局变量
const imgPrefix = inject('imgPrefix');
const route = useRoute();
const router = useRouter();
const {proxy} = getCurrentInstance();
const loginUser = sessionStorage.getItem("loginUser");
console.log(loginUser);
console.log(loginUser.uPic);
console.log(imgPrefix);

const userChange = reactive({
  uid: loginUser.uid,
  username: loginUser.username,
  displayName: loginUser.displayName,
  phone: loginUser.phone,
  uPic: loginUser.uPic,
})
const uPicUrl = ref(imgPrefix + loginUser.uPic);
console.log("用户初始信息：" + JSON.stringify(userChange))
// 用户头像上传历史
let fileList = reactive([])
// 定义表单验证规则
const userInfoRules = reactive({
  username: [
    {required: true, message: '用户名不可为空！', trigger: 'blur'},
    {min: 4, max: 12, message: '用户名长度在4到12个字符之间', trigger: 'blur'},
  ],
  displayName: [
    {required: true, message: '昵称不可为空！', trigger: 'blur'},
    {min: 1, max: 10, message: '昵称长度在1到10位之间', trigger: 'blur'},
  ],
  phone: [
    {required: true, message: '手机号不可为空！', trigger: 'blur'},
    {min: 11, max: 11, message: '手机号长度为11位！', trigger: 'blur'},
  ]
});

const handleUserChange = () => {
  // 头像没变化，ossUPic使用旧的即可，然后直接修改用户信息
  if (uPicUrl.value === imgPrefix + loginUser.uPic) {
    userInfoChange(loginUser.uPic)
  } else {
    // 头像有变化，则先调用后端接口上传oss，利用文件成功上传的回调函数拿到返回给前端的图片名，然后携带输入框信息一起更新
    // 保留最新的最后一个，然后上传
    const uploadRefObj = proxy.$refs.uploadRef;
    uploadRefObj.submit();
  }
}
const fileTypes = ref(["image/bmp", "image/jpeg", "image/png"]);
const beforeUpload = (file) => {
  const fileType = ref();
  fileType.value = file.raw == null ? file.type : file.raw.type;
  if (!fileTypes.value.includes(fileType.value)) {
    ElNotification.error("只能上传bmp/jpeg/jpg/png图片");
    return false;
  }
  if (file.size / 1024 / 1024 > 2) {
    ElNotification.error("上传图片最大不超过2MB!");
    return false;
  }
  return true;
}

// 处理文件改变事件，将文件转为Base64格式并存储在sessionStorage中（同时更新当前显示头像用于预览）
const handleFileChange = (uploadFile, uploadFiles) => {
  if (!beforeUpload(uploadFile.raw)) {
    return;
  }
  // 展示
  const reader = new FileReader();
  reader.onloadend = () => {
    const base64Data = reader.result;
    if (base64Data) {
      // 将Base64数据存储到sessionStorage，键名为'tempAvatar'，方便后续提交时使用
      sessionStorage.setItem('tempAvatar', base64Data);
      uPicUrl.value = base64Data;
    }
  };
  if (uploadFile.raw) {
    console.log("正在读取选择的文件，请稍候...");
    reader.readAsDataURL(uploadFile.raw);
  } else {
    ElNotification.error("没有获取到有效的文件原始数据，无法进行读取操作");
  }

  uploadFiles.forEach(item => {
    console.log("uploadFiles的内容：" + JSON.stringify(item));
  })

  if (uploadFiles.length > 1) {
    const uploadRefObj = proxy.$refs.uploadRef;
    // 1. 清空list
    uploadRefObj.clearFiles();
    // 2. 上传最新的
    uploadRefObj.handleStart(uploadFile.raw);
  }


};


// 文件上传成功后的回调函数
const handleSuccess = (res, file, fileList) => {
  console.log('文件上传成功', res, file, fileList);
  if ('200' === res.code) {
    console.log("后端接口返回正常！");
    const ossUPic = res.data;
    userInfoChange(ossUPic);
  }
};
const userInfoChange = async (ossUPic) => {
  const userInfoRef = proxy.$refs.userInfoRef;
  await userInfoRef.validate((valid) => {
    if (valid) {
      // 此时这里的uPic需要去掉imgPrefix，只保留文件名
      if (uPicUrl.value !== imgPrefix + loginUser.uPic) {
        userChange.uPic = ossUPic;
      }
      console.log("发送修改个人信息请求的参数：" + JSON.stringify(userChange));
      request({
        url: "/user/changeInfo",
        method: "post",
        data: userChange
      }).then(res => {
        if ('200' === res.code) {
          ElNotification({
            type: 'success',
            message: res.msg
          })
          // 清除旧的loginUser，赋值新的loginUser
          sessionStorage.removeItem("loginUser");
          sessionStorage.setItem("loginUser", res.data);
          // 刷新页面
          window.location.reload();
        } else {
          ElNotification({
            type: 'error',
            message: res.data.msg
          })
        }

      })
    } else {
      ElNotification({
        type: 'error',
        message: '输入的用户信息格式错误！'
      })
    }
  })
}
// 文件上传失败后的回调函数
const handleError = (response, file, fileList) => {
  console.log('文件上传失败', response, file, fileList);
  ElNotification.error("图片上传失败！");
};

const cancelUserChange = () => {
  sessionStorage.removeItem("tempAvatar");
  router.push("/home");
}


const passwordChange = reactive({
  uid: loginUser.uid,
  oldPassword: "",
  newPassword: "",
  confirmNewPassword: "",
})
// 自定义确认新密码表单校验
const confirmNewPasswordValid = (rule, value, callback) => {
  if (value === passwordChange.newPassword) {
    callback();
  } else {
    callback(new Error('两次输入的新密码不一致'));
  }
}
// 定义表单验证规则
const changePasswordRules = reactive({
  oldPassword: [
    {required: true, message: '请输入旧密码', trigger: 'blur'}
  ],
  newPassword: [
    {required: true, message: '新密码不可为空！', trigger: 'blur'},
    {min: 6, max: 12, message: '新密码长度在6到12位之间', trigger: 'blur'},
  ],
  confirmNewPassword: [
    {required: true, message: '请再次输入新密码', trigger: 'blur'},
    {validator: confirmNewPasswordValid, trigger: 'blur'}
  ]
});

const handleChangePassword = async () => {
  const formObj = proxy.$refs.passwordRef;
  await formObj.validate((valid) => {

    if (valid) {
      const passwordDto = reactive({
        uid: passwordChange.uid,
        oldPassword: passwordChange.oldPassword,
        newPassword: passwordChange.newPassword,
      })
      console.log("发送修改密码请求的参数：" + JSON.stringify(passwordDto));
      axios.post(
          baseIp + ":9090/user/resetPassword",
          qs.stringify(passwordDto),
          {headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'}}
      ).then(res => {
        if ('200' === res.data.code) {
          ElNotification({
            type: 'success',
            message: "修改密码成功，请重新登录！"
          })
          sessionStorage.removeItem("loginUser")
          router.push("/login");

        } else {
          ElNotification({
            type: 'error',
            message: res.data.msg
          })
        }

      })
    } else {
      ElNotification({
        type: 'error',
        message: '密码格式错误！'
      })
    }
  })
}


const cancelChangePassword = () => {
  router.push("/home");
}
</script>
<style scoped>
#container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 70vh;
}

.tabDiv {
  display: flex;
  width: 500px;
  height: 40vh;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  flex-basis: content;

}


#infoForm .formInput {
  width: 100%;
  margin: 20px 0;
}

.formButton {
  float: right;
  margin-top: 50px;
}
</style>